<template>
  <el-dialog title="" :visible.sync="showDialog" width="50%" @close="handleClose" append-to-body>
    <!-- 评论头部 -->
    <div class="comment-header">
      <span class="comment-count">评论 {{ commentCount }}</span>
    </div>

    <!-- 评论列表滚动容器 -->
    <div class="comment-list-container">
      <!-- 主评论列表 -->
      <div v-for="(comment, cIndex) in comments" :key="`comment_${cIndex}`" class="comment-item">
        <el-avatar
          :size="40"
          :src="comment.icon || 'https://picsum.photos/40/40'"
          class="comment-avatar"
          @click="$emit('clickAuthor', comment)"
        />
        <div class="comment-content-wrap">
          <!-- 评论作者信息 -->
          <div class="comment-author">
            <span class="author-name">{{ comment.name }}</span>
            <img v-if="comment.vip === 1" src="@/assets/images/yuedu.png" width="16px" height="16px" class="vip-icon" />
            <img
              v-if="comment.vip === 2"
              src="@/assets/images/zuanshi.png"
              width="16px"
              height="16px"
              class="vip-icon"
            />
            <img v-if="comment.vip === 3" src="@/assets/images/jika.png" width="16px" height="16px" class="vip-icon" />
          </div>

          <!-- 评论内容 -->
          <div class="comment-text" @click.stop="handleReply(comment)">
            {{ comment.is_like === -1 ? '**********' : comment.content }}
          </div>

          <!-- 评论操作栏 -->
          <div class="comment-actions">
            <span class="comment-time">{{ comment.time_ago }}</span>
            <span class="action-btn reply-btn" @click.stop="handleReply(comment)">回复</span>
            <span
              v-if="comment.is_author === 1"
              @click="handleDelete(comment, cIndex)"
              class="iconfont icon-shanchu action-btn reply-btn"
            ></span>
            <span
              @click="toggleLike(comment, 'comment', 'like')"
              class="iconfont action-btn reply-btn"
              :class="{ 'icon-xihuan1': comment.is_like !== 1, 'like-icon_liked icon-xihuan': comment.is_like === 1 }"
            >
              {{ comment.like_count }}
            </span>
            <span
              @click="toggleLike(comment, 'comment', 'dislike')"
              :class="{ 'icon-buxihuan': comment.is_like !== -1, 'icon-buxihuan1': comment.is_like === -1 }"
              class="iconfont action-btn reply-btn"
            ></span>
          </div>

          <!-- 子评论区域 -->
          <div v-if="comment.subcomment_count" class="subcomment-section">
            <div v-if="!comment.showReplies" class="toggle-reply" @click="toggleReplies(cIndex, true, comment)">
              展开{{ comment.subcomment_count }}条回复
              <i class="el-icon-arrow-down"></i>
            </div>

            <div v-else>
              <!-- 子评论列表 -->
              <div
                v-for="(subComment, sIndex) in comment.replies"
                :key="`subcomment_${sIndex}`"
                class="subcomment-item"
              >
                <el-avatar
                  :size="30"
                  :src="subComment.icon || 'https://picsum.photos/30/30'"
                  class="subcomment-avatar"
                  @click="$emit('clickAuthor', subComment)"
                />
                <div class="subcomment-content">
                  <div class="subcomment-author">
                    <span class="author-name">{{ subComment.name }}</span>
                    <img
                      v-if="subComment.vip"
                      :src="getVipIcon(subComment.vip)"
                      width="14px"
                      height="14px"
                      class="vip-icon"
                    />
                    <span v-if="subComment.is_reply === 1" class="reply-arrow">
                      <i class="el-icon-caret-right"></i>
                    </span>
                    <span v-if="subComment.is_reply === 1" class="reply-to">{{ subComment.reply_user_name }}</span>
                  </div>
                  <div class="subcomment-text" @click.stop="handleReply(subComment, subComment)">
                    {{ subComment.is_like === -1 ? '**********' : subComment.content }}
                  </div>
                  <div class="subcomment-actions">
                    <span class="comment-time">{{ subComment.time_ago }}</span>
                    <span class="action-btn reply-btn" @click.stop="handleReply(comment, subComment)">回复</span>
                    <span
                      v-if="subComment.is_author === 1"
                      @click="handleDelete(subComment, sIndex, 'child', comment)"
                      class="iconfont icon-shanchu action-btn reply-btn"
                    ></span>
                    <span
                      @click="toggleLike(subComment, 'sub_comment', 'like', cIndex, sIndex)"
                      class="iconfont action-btn reply-btn"
                      :class="{
                        'icon-xihuan1': subComment.is_like !== 1,
                        'like-icon_liked icon-xihuan': subComment.is_like === 1,
                      }"
                    >
                      {{ subComment.like_count }}
                    </span>
                    <span
                      @click="toggleLike(subComment, 'sub_comment', 'dislike', cIndex, sIndex)"
                      :class="{
                        'icon-buxihuan': subComment.is_like !== -1,
                        'icon-buxihuan1': subComment.is_like === -1,
                      }"
                      class="iconfont action-btn reply-btn"
                    ></span>
                  </div>
                </div>
              </div>

              <!-- 加载更多/收起回复 -->
              <div
                class="toggle-reply"
                @click="comment.isLoadingAll ? toggleReplies(cIndex, false, comment) : repliesMore(comment, cIndex)"
              >
                {{ comment.isLoadingAll ? '收起回复' : '点击加载更多' }}
                <i :class="comment.isLoadingAll ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 无评论提示 -->
      <div v-if="comments.length === 0 && !isLoading" class="no-comment">
        <el-empty description="暂无评论" />
      </div>

      <!-- 加载中 -->
      <div v-if="isLoading" class="loading-comments">
        <!-- <el-loading-spinner /> -->
        <span class="loading-text">加载中...</span>
      </div>
    </div>

    <!-- 评论输入框 -->
    <div class="comment-input-wrap">
      <el-input
        type="textarea"
        :rows="3"
        v-model="commentText"
        :placeholder="getInputPlaceholder()"
        @keyup.enter.native="submitComment"
      />
      <el-button type="primary" @click="submitComment" class="submit-btn">发送</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { commentsList, commentsListChild, leaveComment, deleteComment, commentsLike } from '@/api/workList'
import { mapGetters } from 'vuex'

export default {
  name: 'CommentDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    workId: {
      type: [String, Number],
      required: true,
    },
    commentCount: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      comments: [],
      commentText: '',
      showDialog: false,
      currentReplyComment: null,
      currentReplyCommentChild: null,
      isLoading: false,
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    // 判断是否已登录（根据 RuoYi 的 token 状态）
  },
  watch: {
    visible(newVal) {
      this.showDialog = newVal
      if (newVal) {
        this.loadComments()
      } else {
        this.resetState()
      }
    },
  },
  methods: {
    // 加载评论列表
    async loadComments() {
      this.isLoading = true
      try {
        const res = await commentsList({
          work_id: this.workId,
          limit: 20,
          cursor: 0,
        })
        if (res.code === 200) {
          this.comments = res.data.items || []
        } else {
          this.$message.error(res.msg || '获取评论失败')
        }
      } catch (error) {
        this.$message.error('获取评论失败')
        console.error(error)
      } finally {
        this.isLoading = false
      }
    },

    // 切换回复展开/收起
    async toggleReplies(cIndex, show, comment) {
      if (show && !comment.replies) {
        await this.loadSubComments(comment, cIndex)
      }
      this.$set(this.comments[cIndex], 'showReplies', show)
    },

    // 加载子评论
    async loadSubComments(comment, cIndex, cursor = 0) {
      try {
        const res = await commentsListChild({
          comment_id: comment.id,
          cursor,
          limit: 20,
        })
        if (res.code === 200) {
          const items = res.data.items || []
          if (comment.replies) {
            comment.replies = this.filterArrId([...comment.replies, ...items])
          } else {
            comment.replies = items
          }
          if (items.length === 0) {
            comment.isLoadingAll = true
          }
          this.$set(this.comments, cIndex, comment)
        } else {
          this.$message.error(res.msg || '获取回复失败')
        }
      } catch (error) {
        this.$message.error('获取回复失败')
        console.error(error)
      }
    },

    // 加载更多子评论
    repliesMore(comment, cIndex) {
      if (!comment.replies || !comment.replies.length) return
      const lastId = comment.replies[comment.replies.length - 1].id
      this.loadSubComments(comment, cIndex, lastId)
    },

    // 处理回复
    handleReply(comment, subComment = null) {
      this.currentReplyComment = comment
      this.currentReplyCommentChild = subComment
      this.$nextTick(() => {
        document.querySelector('.el-textarea__inner')?.focus()
      })
    },

    // 获取输入框占位符
    getInputPlaceholder() {
      if (this.currentReplyCommentChild) {
        return `回复 @${this.currentReplyCommentChild.name}...`
      } else if (this.currentReplyComment) {
        return `回复 @${this.currentReplyComment.name}...`
      }
      return '言语有温度，文字见人心'
    },

    // 提交评论
    async submitComment() {
      const content = this.commentText.trim()
      if (!content) return

      try {
        const params = {
          work_id: this.workId,
          content,
        }
        if (this.currentReplyComment) params.comment_id = this.currentReplyComment.id
        if (this.currentReplyCommentChild) params.subcomment_id = this.currentReplyCommentChild.id

        const res = await leaveComment(params)
        if (res.code === 200) {
          this.$message.success('评论成功')
          this.handleNewComment(res.data, content)
          this.commentText = ''
          this.currentReplyComment = null
          this.currentReplyCommentChild = null
        } else {
          this.$message.error(res.msg || '评论失败')
        }
      } catch (error) {
        this.$message.error('评论失败')
        console.error(error)
      }
    },

    // 处理新评论
    handleNewComment(data, content) {
      console.log(this.userInfo, '6666666')
      const newComment = {
        id: data.subcomment_id || data.comment_id,
        content,
        name: this.userInfo.name || '匿名用户',
        time_ago: '刚刚',
        icon: this.userInfo.icon,
        open_id: this.userInfo.openid,
        like_count: 0,
        vip: this.userInfo.vip || 0,
        is_reply: this.currentReplyCommentChild ? 1 : 0,
        reply_user_name: this.currentReplyCommentChild?.name || this.currentReplyComment?.name || '',
      }

      if (this.currentReplyCommentChild) {
        // 回复子评论
        const parent = this.comments.find(c => c.id === this.currentReplyComment.id)
        if (parent?.replies) parent.replies.unshift(newComment)
      } else if (this.currentReplyComment) {
        // 回复主评论
        const parent = this.comments.find(c => c.id === this.currentReplyComment.id)
        if (parent) {
          if (!parent.replies) parent.replies = []
          parent.replies.unshift(newComment)
          parent.subcomment_count = (parent.subcomment_count || 0) + 1
          parent.showReplies = true
        }
      } else {
        // 新增主评论
        this.comments.unshift({ ...newComment, replies: [] })
      }

      // 通知父组件更新评论数
      this.$emit('update:commentCount', this.commentCount + 1)
    },

    // 删除评论
    async handleDelete(item, index, type, comment) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            const params = type === 'child' ? { subcomment_id: item.id } : { comment_id: item.id }

            const res = await deleteComment(params)
            if (res.code === 200) {
              this.$message.success('删除成功')
              if (type === 'child') {
                const { replies } = comment
                replies.splice(index, 1)
              } else {
                this.comments.splice(index, 1)
              }
              this.$emit('update:commentCount', Math.max(0, this.commentCount - res.data.total))
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          } catch (error) {
            this.$message.error('删除失败')
            console.error(error)
          }
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 移除评论
    removeComment(item, index, type, parentComment, cIndex) {
      if (type === 'sub') {
        parentComment.replies.splice(index, 1)
        this.$set(this.comments, cIndex, parentComment)
      } else {
        this.comments.splice(index, 1)
      }
    },
    // 评论点赞/点踩
    // 评论点赞/点踩 - 替代方案
    async toggleLike(comment, entityType, action, parentIndex = null, childIndex = null) {
      const oldStatus = comment.is_like
      const oldLikeCount = comment.like_count

      // 计算新状态
      let newStatus, newLikeCount
      if (action === 'like') {
        newStatus = oldStatus === 1 ? 0 : 1
        newLikeCount = newStatus === 1 ? oldLikeCount + 1 : oldLikeCount - 1
      } else {
        newStatus = oldStatus === -1 ? 0 : -1
        newLikeCount = oldStatus === 1 ? oldLikeCount - 1 : oldLikeCount
      }

      try {
        // 直接创建新对象替换原对象
        const updatedComment = {
          ...comment,
          is_like: newStatus,
          like_count: newLikeCount,
        }

        if (parentIndex !== null && childIndex !== null) {
          // 更新子评论
          this.comments[parentIndex].replies.splice(childIndex, 1, updatedComment)
          // 强制更新
          this.$set(this.comments, parentIndex, { ...this.comments[parentIndex] })
        } else {
          // 更新主评论
          const commentIndex = this.comments.findIndex(c => c.id === comment.id)
          if (commentIndex !== -1) {
            this.comments.splice(commentIndex, 1, updatedComment)
            this.comments = [...this.comments]
          }
        }

        // 调用接口
        await commentsLike({
          entity_id: comment.id,
          entity_type: entityType,
          action,
        })
      } catch (error) {
        // 回滚状态
        if (parentIndex !== null && childIndex !== null) {
          this.comments[parentIndex].replies.splice(childIndex, 1, {
            ...comment,
            is_like: oldStatus,
            like_count: oldLikeCount,
          })
          this.$set(this.comments, parentIndex, { ...this.comments[parentIndex] })
        }

        this.$message.error('操作失败')
        console.error(error)
      }
    },
    // 评论点赞/点踩
    // async toggleLike(comment, entityType, action) {
    //   const oldStatus = comment.is_like
    //   // 临时更新UI
    //   comment.is_like = action === 'like' ? (oldStatus === 1 ? 0 : 1) : oldStatus === -1 ? 0 : -1
    //   console.log(comment, '555555555')
    //   console.log(this.comments, '6666')
    //   const oldLikeCount = comment.like_count
    //   if (action === 'like') {
    //     const newLikeStatus = oldStatus === 1 ? 0 : 1
    //     this.$set(comment, 'is_like', newLikeStatus)
    //     this.$set(comment, 'like_count', newLikeStatus ? oldLikeCount + 1 : oldLikeCount - 1)
    //   } else if (action === 'dislike') {
    //     const newDislikeStatus = oldStatus === -1 ? 0 : -1
    //     this.$set(comment, 'is_like', newDislikeStatus)
    //     if (oldStatus === 1) {
    //       this.$set(comment, 'like_count', oldLikeCount - 1)
    //     }
    //   }

    //   try {
    //     await commentsLike({
    //       entity_id: comment.id,
    //       entity_type: entityType,
    //       action,
    //     })
    //   } catch (error) {
    //     // 接口失败回滚状态
    //     comment.is_like = oldStatus
    //     if (action === 'like') {
    //       comment.like_count += oldStatus ? 1 : -1
    //     } else if (oldStatus === 1) {
    //       comment.like_count += 1
    //     }
    //     this.$message.error('操作失败')
    //     console.error(error)
    //   }
    // },

    // 获取VIP图标
    getVipIcon(vipLevel) {
      const icons = {
        1: '@/assets/images/yuedu.png',
        2: '@/assets/images/zuanshi.png',
        3: '@/assets/images/jika.png',
      }
      return icons[vipLevel] || ''
    },

    // 过滤重复ID
    filterArrId(arr) {
      const map = new Map()
      arr.forEach(item => map.has(item.id) || map.set(item.id, item))
      return Array.from(map.values())
    },

    // 关闭弹窗时重置状态
    resetState() {
      this.comments = []
      this.commentText = ''
      this.currentReplyComment = null
      this.currentReplyCommentChild = null
    },

    // 通知父组件关闭
    handleClose() {
      this.showDialog = false
      this.$emit('update:visible', false)
      this.resetState()
    },
  },
}
</script>

<style scoped>
.comment-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
::v-deep .el-dialog__body {
  padding-top: 0;
}
.comment-count {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.comment-list-container {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
  padding-right: 10px;
}

.comment-item {
  display: flex;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f5f5f5;
}

.comment-avatar {
  margin-right: 15px;
  cursor: pointer;
}

.comment-content-wrap {
  flex: 1;
}

.comment-author {
  display: flex;
  align-items: center;
}

.author-name {
  font-weight: 500;
  margin-right: 8px;
}

.vip-icon {
  margin-right: 8px;
}

.comment-text {
  margin: 8px 0;
  line-height: 1.5;
}

.comment-actions {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}
.like-icon_liked,
.like-icon_check {
  color: #e60012 !important;
}
.comment-time {
  margin-right: 15px;
}

.action-btn {
  margin-right: 15px;
  cursor: pointer;
  /* background-color: #292424; */
  transition: color 0.2s;
}

.action-btn:hover {
  color: #409eff;
}

.delete-btn {
  color: #f56c6c;
}
:deep(.iconfont) {
  font-size: 20px !important;
  width: 20px !important;
  height: 20px !important;
}
.delete-btn:hover {
  color: #e4393c;
}

.like-icon,
.dislike-icon {
  width: 16px;
  height: 16px;
  margin-right: 4px;
  vertical-align: middle;
}

.like-icon.active {
  filter: invert(27%) sepia(99%) saturate(7491%) hue-rotate(355deg) brightness(105%) contrast(116%);
}

.dislike-icon.active {
  filter: invert(27%) sepia(99%) saturate(7491%) hue-rotate(355deg) brightness(105%) contrast(116%);
}

.subcomment-section {
  margin-left: 20px;
  margin-top: 15px;
}

.subcomment-item {
  display: flex;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #f5f5f5;
}

.subcomment-avatar {
  margin-right: 10px;
  cursor: pointer;
}

.subcomment-content {
  flex: 1;
}

.subcomment-author {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.reply-arrow {
  /* margin: 0 3px; */
  margin-right: 3px;
  margin-top: 2px;
  font-size: 14px;
  color: #999;
}

.reply-to {
  color: #666;
  font-weight: 500;
}

.subcomment-text {
  margin: 5px 0;
  font-size: 13px;
  line-height: 1.5;
}

.subcomment-actions {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.toggle-reply {
  font-size: 12px;
  color: #666;
  cursor: pointer;
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.toggle-reply i {
  margin-left: 5px;
  font-size: 14px;
}

.comment-input-wrap {
  display: flex;
  gap: 10px;
}

.submit-btn {
  align-self: flex-end;
}

.no-comment {
  text-align: center;
  padding: 40px 0;
}

.loading-comments {
  text-align: center;
  padding: 40px 0;
}

.loading-text {
  display: inline-block;
  margin-left: 10px;
  color: #666;
}
</style>
